//
//  ExLocationAuthorizationViewController.m
//  OC-Example
//
//  Created by iOS_Doule on 2019/2/11.
//  Copyright © 2019 apang.men. All rights reserved.
//

#import "ExLocationAuthorizationViewController.h"
#import <CoreLocation/CoreLocation.h>
@interface ExLocationAuthorizationViewController ()<CLLocationManagerDelegate>
@property (strong, nonatomic) UIButton *startButton;
@property (strong, nonatomic) CLLocationManager * locationManager;
@end

@implementation ExLocationAuthorizationViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self.view setBackgroundColor:[UIColor whiteColor]];
    // Do any additional setup after loading the view.
    // !!!: 在info.plist文件中增加四个描述
    /*
     NSLocationAlwaysUsageDescription 10.0 以前 申请一直使用
     NSLocationAlwaysAndWhenInUseUsageDescription 2.0版本以后
     NSLocationUsageDescription 6.0版本
     NSLocationWhenInUseUsageDescription 8.0 仅在运行时
     */
    self.title = @"申请定位权限";
    UIButton * permissionBtn = [UIButton buttonWithType:UIButtonTypeSystem];
    [permissionBtn setTitle:@"申请定位权限" forState:UIControlStateNormal];
    [permissionBtn addTarget:self action:@selector(permission:) forControlEvents:UIControlEventTouchUpInside];
    [permissionBtn setTranslatesAutoresizingMaskIntoConstraints:NO];
    [self.view addSubview:permissionBtn];
    
    [self.view addConstraint:[NSLayoutConstraint constraintWithItem:permissionBtn attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeCenterX multiplier:1.0 constant:0.0]];
    [self.view addSubview:self.startButton];
    [self.view addConstraint:[NSLayoutConstraint constraintWithItem:self.startButton attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeCenterX multiplier:1.0 constant:0.0]];
    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-(20)-[permissionBtn]-(5)-[_startButton]" options:0 metrics:nil views:NSDictionaryOfVariableBindings(permissionBtn,_startButton)]];
}
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    CLAuthorizationStatus authorization = [CLLocationManager authorizationStatus];
    
    switch (authorization) {
        case kCLAuthorizationStatusNotDetermined:
            NSLog(@"用户尚未就此应用程序做出选择");
            [self permission:nil];
            break;
        case kCLAuthorizationStatusRestricted:
            NSLog(@"用户跳过了授权");
            [self permission:nil];
            break;
        case kCLAuthorizationStatusDenied:
            NSLog(@"用户已明确拒绝此应用程序的授权，或在“设置”中禁用了位置服务。");
            [self permission:nil];
            break;
        case kCLAuthorizationStatusAuthorizedAlways:
            NSLog(@"用户允许一直使用定位权限包含后台定位");
            break;
        case kCLAuthorizationStatusAuthorizedWhenInUse:
            NSLog(@"仅允许前台使用定位");
            break;
        default:
            break;
    }
}

- (void)permission:(id)sender {
    // !!!:   这个 申请的是一直使用定位权限(后台)
    //    [self.locationManager requestAlwaysAuthorization];
    //只有在app前台运行的时候可以使用定位;
    [self.locationManager requestWhenInUseAuthorization];
}
- (void)start:(UIButton *)sender {
    if (sender.selected) {
        NSLog(@"停止定位");
        [self.locationManager stopUpdatingLocation];
    }else {
        NSLog(@"开始定位");
        [self.locationManager startUpdatingLocation];
    }
    sender.selected = !sender.selected;
}

//MARK: - CLLocationManager‘s Delegate

- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations {
    CLLocation *location = [locations lastObject];
    NSLog(@"经度:%f  纬度：%f",location.coordinate.longitude,location.coordinate.latitude);
}

- (CLLocationManager *)locationManager {
    if (!_locationManager) {
        _locationManager = [[CLLocationManager alloc] init];
        _locationManager.delegate = self;
    }
    return _locationManager;
}

- (UIButton *)startButton {
    if (!_startButton) {
        _startButton = [UIButton buttonWithType:UIButtonTypeSystem];
        [_startButton setTitle:@"开始" forState:UIControlStateNormal];
        [_startButton setTitle:@"结束" forState:UIControlStateSelected];
        [_startButton addTarget:self action:@selector(start:) forControlEvents:UIControlEventTouchUpInside];
        [_startButton setTranslatesAutoresizingMaskIntoConstraints:NO];
    }
    return _startButton;
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
